package com.xzp.blog.service.impl;

import com.xzp.blog.entity.User;
import com.xzp.blog.entity.dto.form.UserLoginForm;
import com.xzp.blog.entity.dto.form.UserRegisterForm;
import com.xzp.blog.mapper.UserMapper;
import com.xzp.blog.service.IUserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

import static com.xzp.blog.consts.SessionConstants.SESSION_CURRENT_USER;

/**
 * 用户信息实现类
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 登录验证
     * @param loginForm 登陆表单
     * @return
     */
    @Override
    public User loginAuthentication(UserLoginForm loginForm) {
        User user = new User();
        user.setUsername(loginForm.getUsername());
        user.setPassword(DigestUtils.md5Hex(loginForm.getPassword()));
        List<User> userList = userMapper.select(user);
        if (userList != null && userList.size() == 1)
            return userList.get(0);

        return null;
    }

    @Override
    public boolean registerUsernameCheckExist(UserRegisterForm registerForm) {
        User user = new User();
        user.setUsername(registerForm.getUsername());
        List<User> userList = userMapper.select(user);
        if (userList.size() > 0)
            return true;
        return false;
    }

    @Override
    public void insertUser(User user) {
        String pwdStr = user.getPassword();
        user.setPassword(DigestUtils.md5Hex(pwdStr));
        userMapper.insertSelective(user);  //插入一条数据，只插入不为null的字段
    }

    @Override
    public void joinSession(HttpServletRequest request, User user) {
        HttpSession session = request.getSession(true);
        session.setAttribute(SESSION_CURRENT_USER,user);  //设置当前用户
    }

    /**
     * 注销
     * @param request
     */
    @Override
    public void destroySession(HttpServletRequest request) {
        HttpSession session = request.getSession(true);
        session.removeAttribute(SESSION_CURRENT_USER);
    }
}
